<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class init_table extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'songshu:init_table';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '重置整个树';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle($page=1)
    {
        $size = 500;
        $begin = ($page-1)*$size;
        $all = DB::table('userdata')->where([
            ['tj_id','>',0],
        ])->orderBy('id','asc')->offset($begin)->limit($size);

        foreach($all as $item){
            $father = DB::table('user_tree')->where('uid',$item->tj_id)->first();
            if(empty($father) || $item->id<$item->tj_id){
                $data = [
                    'uid'=>$item->id,
                    'pid'=>$item->tj_id,
                    'tree_id'=>$item->id,
                    'left'=>1,
                    'right'=>2,
                    'hight'=>0
                ];
                DB::table('user_tree')->insertGetId($data);
            }else{
                $data = [
                    'uid'=>$item->id,
                    'pid'=>$item->tj_id,
                    'tree_id'=>$father->tree_id,
                    'left'=>$father->right,
                    'right'=>$father->right+1,
                    'hight'=>$father->hight+1,
                ];
                DB::beginTransaction();
                #修改右节点
                $step1 = DB::table('user_tree')->where([
                    ['tree_id','=',$father->tree_id],
                    ['left','>',$father->left],
                ])->update([
                    'left'=>DB::raw("`left`+2"),
                    'right'=>DB::raw("`right`+2")
                ]);
                #修改父
                $step2 = DB::table('user_tree')->where([
                    ['tree_id','=',$father->tree_id],
                    ['left','<=',$father->left],
                    ['right','>=',$father->right],
                ])->update([
                    'right'=>DB::raw("`right`+2")
                ]);
                #插表
                $step3 = DB::table('user_tree')->insertGetId($data);
                
                if($step1!==false && $step2!==false && $step3!==false){
                    DB::commit();
                    return $step3;
                }else{
                    DB::rollBack();
                    return false;
                }
            }
        }
        $page++;
        $this->handle($page);
    }
}
